import 'dart:async';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

abstract class BaseWebSocketService extends GetxService {
  WebSocketChannel? channel;
  StreamSubscription? subscription;
  RxBool isConnected = false.obs;
  late String url;
  late int userId;

  BaseWebSocketService(String baseUrl, this.userId) {
    url = "$baseUrl/$userId";
    print("用户${userId}, 尝试连接");
  }

  /// ✅ 初始化连接
  Future<void> init() async {
    try {
      print("🔌 正在连接 WebSocket: $url");
      channel = WebSocketChannel.connect(Uri.parse(url));
      isConnected.value = true;

      subscription = channel!.stream.listen((msg) => onMessage(msg), onDone: onDone, onError: onError);

      print("✅ 连接成功: $url");
    } catch (e) {
      print("❌ WebSocket 连接失败: $url, $e");
      reconnect();
    }
  }

  /// ✅ 接收到消息（子类实现）
  void onMessage(dynamic msg);

  /// ✅ 出现错误
  void onError(error) {
    print("❌ [$url] WebSocket 错误: $error");
    isConnected.value = false;
    reconnect();
  }

  /// ✅ 连接关闭
  void onDone() {
    print("⚠️ [$url] WebSocket 已断开");
    isConnected.value = false;
    reconnect();
  }

  /// ✅ 自动重连
  void reconnect() {
    Future.delayed(const Duration(seconds: 3), () {
      if (!isConnected.value) {
        print("🔁 [$url] 尝试重新连接...");
        init();
      }
    });
  }

  /// ✅ 发送消息
  void send(Map<String, dynamic> data) {
    if (channel == null) {
      print("⚠️ [$url] WebSocket 未连接，无法发送");
      return;
    }
    final jsonStr = jsonEncode(data);
    channel!.sink.add(jsonStr);
    print("📤 [$url] 发送消息: $jsonStr");
  }

  /// ✅ 关闭连接
  void close() {
    subscription?.cancel();
    channel?.sink.close();
    isConnected.value = false;
    print("🔌 [$url] WebSocket 已关闭");
  }
}
